﻿
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

namespace TP_Link_HTTP_Lib
{
	/// <summary>
	/// Description of MyClass.
	/// </summary>
	public class TPLinkHTTP
	{
		private string routerHost = "192.168.1.1";
		private int routerPort = 80;
		private string routerAdminer = "admin";
		private string routerPassword = "admin";
		private string authHeaders;
		public static bool socHttpReq(string host, int port, string data1, string data2 = "")
		{
			IPAddress tip = IPAddress.Parse(host);
			IPEndPoint ipEnd = new IPEndPoint(tip, port);
			try
			{
				Socket socNet = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				socNet.SendTimeout = 5000;
				socNet.Connect(ipEnd);
				socNet.Send(Encoding.UTF8.GetBytes(data1));
				if (data2 != "")
					socNet.Send(Encoding.UTF8.GetBytes(data2));
				Thread.Sleep(100);
				socNet.Shutdown(SocketShutdown.Both);
				socNet.Close();
				return true;
			}
			catch { return false; }
		}
		public TPLinkHTTP(string host, int port, string adminUsername, string adminPassword)
		{
			routerHost = host;
			routerPort = port;
			routerAdminer = adminUsername;
			routerPassword = adminPassword;
			StringBuilder hdTmp = new StringBuilder();
			hdTmp.Append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n");
			hdTmp.Append("User-Agent: Mozilla/4.0 (Windows NT; rv:1.0) DotNet/2.0 CMCCTRouterDailer/1.10\r\n");
			hdTmp.Append("Host: " + routerHost).Append("\r\n");
			hdTmp.Append("Authorization: Basic ").Append(Convert.ToBase64String(Encoding.ASCII.GetBytes(routerAdminer + ":" + routerPassword))).Append("\r\n");
			hdTmp.Append("Connection: keep-alive\r\n");
			hdTmp.Append("\r\n");
			authHeaders = hdTmp.ToString();
		}
		public bool sendPPPoEConfig(string pppoeUsername, string pppoePassword, string offlineTTL = "0")
		{
			return socHttpReq(routerHost, routerPort, "GET /userRpm/PPPoECfgRpm.htm?wan=0&wantype=2&acc=" + pppoeUsername + "&psw=" + pppoePassword + "&confirm=" + pppoePassword + "&specialDial=100&SecType=0&sta_ip=0.0.0.0&sta_mask=0.0.0.0&linktype=4&waittime2=" + offlineTTL + "&Save=%B1%A3+%B4%E6 HTTP/1.0\r\n" + authHeaders);
		}
		public bool reConnect()
		{
			return socHttpReq(routerHost, routerPort, "GET /userRpm/StatusRpm.htm?Connect=%C1%AC%20%BD%D3&wan=1 HTTP/1.0\r\n" + authHeaders);
		}
	}
}